{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 标准库函数 math/os/random/datetime\n",
    "import math \n",
    "math.floor(3.6) # 向下取整\n",
    "help(math.isclose)  # 获取相关函数的帮助"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.getcwd()\n",
    "# os.rename('A.txt','B.txt')  # 将A文件命名为B文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "print(os.path.isdir(r'E:\\software\\Python\\crawler\\00-风变python\\2-风变python课程资料【基础语法+爬虫精进】\\Python基础语法\\15~17关：第5个小目标：用Python给朋友发个邮件'))\n",
    "print(os.getcwd())\n",
    "path = r'E:\\software\\Python\\abv'  #在路径下创建名为abv的文件夹\n",
    "os.mkdir(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "print(\n",
    "    random.choice(['A','B','C']),'\\n',\n",
    "    random.randint(1,100),'\\n',\n",
    "    random.random(),'\\n',\n",
    "    random.sample(['A','B','C'],2)\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 查模块户口的方法 【看一个库有哪些函数可用】/ 也可用help()函数\n",
    "import random\n",
    "list1 = dir(random)   #  其中 '__xx__'  不用管\n",
    "print(list1)\n",
    "\n",
    "for i in list1 :\n",
    "    if '__' in i:\n",
    "        list1.remove(i)\n",
    "\n",
    "print(list1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 针对模块做笔记【以random为例】\n",
    "import random  # 调用random模块，以下均调用其中函数\n",
    "\n",
    "a = random.random()  # 随机从0-1之间抽取一个浮点数\n",
    "print(a)\n",
    "\n",
    "a = random.randint(0,100)  # 随机从0-100之间抽取一个数字\n",
    "print(a)\n",
    "\n",
    "a = random.choice('abcdefg')  # 随机从字符串/列表/字典等对象中抽取一个元素（可能会重复）\n",
    "print(a)\n",
    "\n",
    "a = random.sample('abcdefg', 3) # 随机从字符串/列表/字典等对象中抽取多个不重复的元素\n",
    "print(a)\n",
    "\n",
    "items = [1, 2, 3, 4, 5, 6]  # “随机洗牌”，比如打乱列表\n",
    "random.shuffle(items)\n",
    "print(items)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "from datetime import date\n",
    "from datetime import time\n",
    "\n",
    "print(\n",
    "    datetime.now(),'\\n',\n",
    "    date.today(),'\\n',\n",
    "    time(),'\\n'\n",
    ")\n",
    "\n",
    "help(datetime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# time 模块作业\n",
    "import time\n",
    "input(\"欢迎使用“时间管理器”！请按回车继续。\")\n",
    "\n",
    "task_name = input('请输入任务名：')\n",
    "task_time = int(input('你觉得自己至少可以专注这个任务多少分钟？输入 N 分钟'))\n",
    "input('此次任务信息：\\n我要完成的任务：%s\\n我至少要专注：%d分钟\\n按回车开始计时：'%(task_name,task_time))\n",
    "start = time.time()  # 开始计时\n",
    "start_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))  # 格式化日期\n",
    "for t in range(task_time*60,0,-1):  # 实际代码：分钟转成秒要乘60，用-1来倒计时。\n",
    "    info = '请专注任务，还要保持专注 ' + str(t) + ' 秒哦！'\n",
    "    print(info,end=\"\")\n",
    "    print(\"\\b\"*(len(info)*2),end=\"\",flush=True)\n",
    "    time.sleep(1)\n",
    "print('你已经专注了 %d 分钟，很棒~再加把劲，完成任务！'%task_time)  # 倒计时后，才继续运行之后的代码。\n",
    "    \n",
    "#     # 询问任务是否完成\n",
    "#     task_status = input('请在任务完成后按输入y:')\n",
    "#     if task_status == 'y':\n",
    "#         end = time.time()  # 一定用户按了 y，就记下结束时间。\n",
    "#         end_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))  # 日期格式化\n",
    "#         actual_time = int((end -start)/60)  # 始末时间相减，从秒换算到分，除以60。\n",
    "#         start_end = start_time + '——' + end_time + '\\n'\n",
    "#         with open('timelog3.txt','a', encoding = 'utf-8') as f:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1×1=1   \n1×2=2  2×2=4   \n1×3=3  2×3=6  3×3=9   \n1×4=4  2×4=8  3×4=12  4×4=16   \n1×5=5  2×5=10  3×5=15  4×5=20  5×5=25   \n1×6=6  2×6=12  3×6=18  4×6=24  5×6=30  6×6=36   \n1×7=7  2×7=14  3×7=21  4×7=28  5×7=35  6×7=42  7×7=49   \n1×8=8  2×8=16  3×8=24  4×8=32  5×8=40  6×8=48  7×8=56  8×8=64   \n1×9=9  2×9=18  3×9=27  4×9=36  5×9=45  6×9=54  7×9=63  8×9=72  9×9=81   \n"
     ]
    }
   ],
   "source": [
    "# 九九乘法表\n",
    "for n in range(1,10):\n",
    "    for i in range(1,10):\n",
    "        if i <= n :\n",
    "            print('%d×%d=%d'%(i,n,n*i),end='  ')\n",
    "#     print('\\n')\n",
    "    print(' ')    #控制换行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业8.1      做题时间30min!不要用C语言思维，多查表\n",
    "A=[91, 95, 97, 99]\n",
    "B=[92, 93, 96, 98]\n",
    "C = A + B  \n",
    "print(C)\n",
    "length = len(C)\n",
    "for r in range(7):\n",
    "    for i in range(len(C)-1):\n",
    "        b = C[i]\n",
    "        if C[i]>C[i+1]:\n",
    "            pass\n",
    "        else:\n",
    "            C[i]=C[i+1]\n",
    "            C[i+1] = b\n",
    "\n",
    "#         length -= 1\n",
    "# C.sort(reverse = True)\n",
    "print(C)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业8.2\n",
    "import numpy\n",
    "A=[91, 95, 97, 99]\n",
    "B=[92, 93, 96, 98]\n",
    "Auder = []\n",
    "Buder = []\n",
    "aveA = numpy.mean(A)\n",
    "aveB = numpy.mean(B)\n",
    "print('A组平均值为%s,B组平均值为%s'%(aveA,aveB))\n",
    "for i in A:\n",
    "    if i < aveA:\n",
    "        Auder.append(i)\n",
    "for i in B:\n",
    "    if i < aveB:\n",
    "        Buder.append(i)\n",
    "print(Auder+Buder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 函数：“喂”给函数一些数据，它就能内部消化，给你“吐”出你想要的东西\n",
    "\n",
    "def  menu(appetizer,course,dessert='绿豆沙'):#位置参数+关键字参数(关键字参数在位置参数后)\n",
    "    'docstring内容:选择菜单点什么菜'\n",
    "    print('一份开胃菜：'+appetizer)\n",
    "    print('一份主食：'+course)\n",
    "    print('一份甜品：'+dessert)\n",
    "\n",
    "menu('话梅花生','牛肉拉面')\n",
    "menu('牛肉拉面','话梅花生')\n",
    "menu(course='牛肉拉面',appetizer='话梅花生')\n",
    "#因为已经默认将'绿豆沙'传递给dessert，调用时无须再传递\n",
    "menu('话梅花生','牛肉拉面','银耳羹')\n",
    "#一个萝卜一个坑，Python会自动将'银耳羹'传递给参数dessert"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def menu(*barbeque):    #不定长参数\n",
    "    print(barbeque)\n",
    "\n",
    "menu('烤鸡翅','烤茄子','烤玉米')\n",
    "\n",
    "#这几个值都会传递给参数barbeque\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def menu(appetizer,course,*barbeque,desert='樱桃'):\n",
    "    print('一份开胃菜：'+appetizer)\n",
    "    print('一份主食：'+course)\n",
    "    print('一份甜品：'+desert)\n",
    "    for i in barbeque:     #遍历元组\n",
    "        print('一份烧烤：'+i)\n",
    "menu('毛豆','糖醋排骨','烤茄子','生蚝')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "###返回值：在很多时候，当多个函数之间相互配合时，需要将某个返回值先放着，等到需要的时候再做进一步的处理。\n",
    "def face(name):\n",
    "    return name+'的脸蛋'\n",
    "def body(name):\n",
    "    return name+'的身材'\n",
    "def main(dreamlover,lover):    #定义主函数来调用各个函数\n",
    "    print('梦中情人：'+face(dreamlover)+body(lover))\n",
    "main('李若彤','林志玲')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#返回多个值，python独特之处\n",
    "\n",
    "def lover(name1,name2):\n",
    "    face = name1 + '的脸蛋'\n",
    "    body = name2 + '的身材'\n",
    "    return face,body    #返回值放入元组\n",
    "a=lover('李若彤','林志玲')\n",
    "print(a)\n",
    "print(type(a))     #元组数据类型\n",
    "print('我的梦中情人：'+a[0]+' + '+a[1])#元组的调用与列表一致"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#没有return语句的函数会默认返回None值\n",
    "def fun():\n",
    "    a ='I am coding'\n",
    "print(fun())\n",
    "\n",
    "#正解\n",
    "def fun():\n",
    "    a='I am coding'\n",
    "    return a\n",
    "print(fun())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_add(x,y):\n",
    "    return x+y\n",
    "a = my_add(1,2)\n",
    "\n",
    "# 匿名函数写法\n",
    "b = lambda x,y:x+y  # 返回值直接赋值\n",
    "a,b(1,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "['d', 'fs', 'afd', 'afds f']"
      ]
     },
     "metadata": {},
     "execution_count": 5
    }
   ],
   "source": [
    "# 匿名函数可以作为函数的参数直接传值\n",
    "def applyToList(sList,f):\n",
    "    return [f(x) for x in sList]\n",
    "ints = [4,0,1,5,6]\n",
    "applyToList(ints,lambda x:x*2)\n",
    "\n",
    "# 直接将匿名函数传给函数的方法\n",
    "strings = ['afd','afds f','fs','d']\n",
    "strings.sort(key=lambda x:len(set(x)))\n",
    "strings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "10\n20\n"
     ]
    }
   ],
   "source": [
    "# 函数传参，参数为字典\n",
    "def printWhat(params):\n",
    "    for i in params:\n",
    "        print(params[i])\n",
    "# printWhat(params['a']=10)   # keyword can't be an expression 传参方式错误，需要整个字典赋值\n",
    "printWhat(params = {'a':10,'v':20})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x=99   #全局变量x  \n",
    "def num():\n",
    "    x=88 #局部变量x \n",
    "    print(x)\n",
    "    \n",
    "num() \n",
    "#打印局部变量x\n",
    "\n",
    "print(x) \n",
    "#打印全局变量x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Generating squares from 1 to 100\n1 4 9 16 25 36 49 64 81 100 "
     ]
    }
   ],
   "source": [
    "# 生成器 : 只需将函数return替换成yield\n",
    "# 和迭代器一样构造可遍历对象,迭代器执行一次返回单个结果\n",
    "# 生成器返回一个多结果序列???\n",
    "def squares(n=10):\n",
    "    print('Generating squares from 1 to {0}'.format(n**2))\n",
    "    for i in range(1,n+1):\n",
    "        yield i**2\n",
    "# 调用生成器时代码不会执行,直到请求生成器中的元素时才会执行\n",
    "gen = squares()\n",
    "for x in gen:\n",
    "    print(x,end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "<generator object <genexpr> at 0x000001DEC8F05648>"
      ]
     },
     "metadata": {},
     "execution_count": 11
    }
   ],
   "source": [
    "# 生成器表达式: 将列表推导式[]改为()\n",
    "gen = (x**2 for x in range(100))\n",
    "gen"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业9.1\n",
    "import random\n",
    "def prize(*player):\n",
    "    a = random.choice(player)\n",
    "    print (a)\n",
    "prize('糖醋排骨','白菜','白切鸡')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#前一章游戏\n",
    "import time\n",
    "import random\n",
    "\n",
    "player_victory = 0\n",
    "enemy_victory = 0\n",
    "\n",
    "while True:\n",
    "    for i in range(1,4):\n",
    "        time.sleep(1.5)\n",
    "        print('  \\n——————现在是第 %s 局——————' % i)\n",
    "        player_life = random.randint(100,150)\n",
    "        player_attack = random.randint(30,50)\n",
    "        enemy_life = random.randint(100,150)\n",
    "        enemy_attack = random.randint(30,50)\n",
    "\n",
    "        print('【玩家】\\n血量：%s\\n攻击：%s' % (player_life,player_attack))\n",
    "        print('------------------------')\n",
    "        time.sleep(1)\n",
    "        print('【敌人】\\n血量：%s\\n攻击：%s' % (enemy_life,enemy_attack))\n",
    "        print('-----------------------')\n",
    "        time.sleep(1)\n",
    "\n",
    "        while player_life > 0 and enemy_life > 0:\n",
    "            player_life = player_life - enemy_attack \n",
    "            enemy_life = enemy_life - player_attack\n",
    "            print('你发起了攻击，【玩家】剩余血量%s' % player_life)\n",
    "            print('敌人向你发起了攻击，【敌人】的血量剩余%s' % enemy_life)\n",
    "            print('-----------------------')\n",
    "            time.sleep(1.2)\n",
    "\n",
    "        if player_life > 0 and enemy_life <= 0:\n",
    "            player_victory += 1\n",
    "            print('敌人死翘翘了，你赢了！')\n",
    "        elif player_life <= 0 and enemy_life > 0:\n",
    "            enemy_victory += 1\n",
    "            print('悲催，敌人把你干掉了！')\n",
    "        else:\n",
    "            print('哎呀，你和敌人同归于尽了！')\n",
    "\n",
    "    if player_victory > enemy_victory :\n",
    "        time.sleep(1)\n",
    "        print('\\n【最终结果：你赢了！】')\n",
    "    elif enemy_victory > player_victory:\n",
    "        print('\\n【最终结果：你输了！】')\n",
    "    else: \n",
    "        print('\\n【最终结果：平局！】')\n",
    "    answer = input('是否要再来一盘：')\n",
    "    if answer == '是':\n",
    "        pass \n",
    "    else:\n",
    "        print('游戏结束！')\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#1.0\n",
    "def show_role(player_life,player_attack,enemy_life,enemy_attack):\n",
    "    print('【玩家】\\n血量：%s\\n攻击：%s'%(player_life,player_attack))\n",
    "    print('------------------------')\n",
    "    print('【敌人】\\n血量：%s\\n攻击：%s'%(enemy_life,enemy_attack))\n",
    "    print('-----------------------')\n",
    "\n",
    "def PK(player_life,player_attack,enemy_life,enemy_attack):\n",
    "    while player_life > 0 and enemy_life > 0:\n",
    "        player_life = player_life - enemy_attack \n",
    "        enemy_life = enemy_life - player_attack\n",
    "        print('你发起了攻击，【敌人】剩余血量%s'%(enemy_life))\n",
    "        print('敌人向你发起了攻击，【玩家】的血量剩余%s'%(player_life))\n",
    "        print('-----------------------')\n",
    "        show_result(player_life,enemy_life)   #函数调用不分前后\n",
    "\n",
    "def show_result(player_life,enemy_life):\n",
    "    if player_life > 0 and enemy_life <= 0:\n",
    "        print('敌人死翘翘了，这局你赢了')\n",
    "    elif player_life <= 0 and enemy_life > 0:\n",
    "        print('悲催，这局敌人把你干掉了！')\n",
    "    else:\n",
    "        print('哎呀，这局你和敌人同归于尽了！')\n",
    "    print('-----------------------')\n",
    "    \n",
    "def main(player_life,player_attack,enemy_life,enemy_attack):\n",
    "    show_role(player_life,player_attack,enemy_life,enemy_attack)\n",
    "    PK(player_life,player_attack,enemy_life,enemy_attack)\n",
    "\n",
    "main(100,35,105,33)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#2.0\n",
    "import random\n",
    "\n",
    "player_list =  ['【狂血战士】','【森林箭手】','【光明骑士】','【独行剑客】','【格斗大师】','【枪弹专家】']\n",
    "enemy_list = ['【暗黑战士】','【黑暗弩手】','【暗夜骑士】','【嗜血刀客】','【首席刺客】','【陷阱之王】']\n",
    "players = random.sample(player_list,3)  \n",
    "enemies = random.sample(enemy_list,3)\n",
    "player_info = {}\n",
    "enemy_info = {}\n",
    "\n",
    "# 随机生成两种属性\n",
    "def born_role():\n",
    "    life = random.randint(100,180)\n",
    "    attack = random.randint(30,50)\n",
    "    return life,attack  # return 多个元素时，返回一个元组（昨天课堂有讲）\n",
    "    \n",
    "# 给角色生成随机属性，并展示角色信息。\n",
    "def show_role():\n",
    "    for i in range(3):\n",
    "        player_info[players[i]] = born_role()\n",
    "        enemy_info[enemies[i]] = born_role()\n",
    "    \n",
    "    # 展示我方的3个角色\n",
    "    print('----------------- 角色信息 -----------------')\n",
    "    print('你的人物：')\n",
    "    for i in range(3):\n",
    "        print('%s  血量：%d  攻击：%d' \n",
    "        %(players[i],player_info[players[i]][0],player_info[players[i]][1]))\n",
    "    print('--------------------------------------------')\n",
    "    print('电脑敌人：')\n",
    "    \n",
    "    # 展示敌方的3个角色\n",
    "    for i in range(3):\n",
    "        print('%s  血量：%d  攻击：%d' \n",
    "        %(enemies[i],enemy_info[enemies[i]][0],enemy_info[enemies[i]][1]))\n",
    "    print('--------------------------------------------')\n",
    "\n",
    "show_role()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#指定顺序排序\n",
    "list1 = ['A','B','C']\n",
    "dict = {}\n",
    "for i in range(3):\n",
    "    order = int(input('你要把'+list1[i]+'放在第几位？（请输入数字1,2,3)'))\n",
    "    dict[order] = list1[i]\n",
    "list = []\n",
    "for i in range(1,4):\n",
    "    list.append(dict[i])\n",
    "print(list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#3.0\n",
    "import random\n",
    "\n",
    "# 将需要的数据和固定变量放在开头\n",
    "player_list =  ['【狂血战士】','【森林箭手】','【光明骑士】','【独行剑客】','【格斗大师】','【枪弹专家】']\n",
    "enemy_list = ['【暗黑战士】','【黑暗弩手】','【暗夜骑士】','【嗜血刀客】','【首席刺客】','【陷阱之王】']\n",
    "players = random.sample(player_list,3)  \n",
    "enemies = random.sample(enemy_list,3)\n",
    "player_info = {}\n",
    "enemy_info = {}\n",
    "\n",
    "# 随机生成角色的属性\n",
    "def born_role():\n",
    "    life = random.randint(100,180)\n",
    "    attack = random.randint(30,50)\n",
    "    return life,attack\n",
    "\n",
    "# 生成和展示角色信息\n",
    "def show_role():\n",
    "    for i in range(3):\n",
    "        player_info[players[i]] = born_role()\n",
    "        enemy_info[enemies[i]] = born_role()\n",
    "    \n",
    "    # 展示我方的3个角色\n",
    "    print('----------------- 角色信息 -----------------')\n",
    "    print('你的人物：')\n",
    "    for i in range(3):\n",
    "        print('%s  血量：%d  攻击：%d' \n",
    "        %(players[i],player_info[players[i]][0],player_info[players[i]][1]))\n",
    "    print('--------------------------------------------')\n",
    "    print('电脑敌人：')\n",
    "    \n",
    "    # 展示敌方的3个角色\n",
    "    for i in range(3):\n",
    "        print('%s  血量：%d  攻击：%d' \n",
    "        %(enemies[i],enemy_info[enemies[i]][0],enemy_info[enemies[i]][1]))\n",
    "    print('--------------------------------------------')\n",
    "    input('请按回车键继续。\\n')  # 为了让玩家更有控制感，可以插入类似的代码来切分游戏进程。\n",
    "\n",
    "# 角色排序，选择出场顺序。\n",
    "def order_role(): \n",
    "    global players\n",
    "    order_dict = {}\n",
    "    for i in range(3):\n",
    "        order = int(input('你想将 %s 放在第几个上场？(输入数字1~3)'%(players[i])))\n",
    "        order_dict[order] = players[i]  \n",
    "\n",
    "    players = []\n",
    "    for i in range(1,4):\n",
    "        players.append(order_dict[i]) \n",
    "    \n",
    "    print('\\n我方角色的出场顺序是：%s、%s、%s' %(players[0],players[1],players[2]))\n",
    "    print('敌方角色的出场顺序是：%s、%s、%s' %(enemies[0],enemies[1],enemies[2]))\n",
    "\n",
    "def main():\n",
    "    show_role()\n",
    "    order_role()\n",
    "\n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#4.0\n",
    "import time,random\n",
    "\n",
    "# 需要的数据和变量放在开头\n",
    "player_list =  ['【狂血战士】','【森林箭手】','【光明骑士】','【独行剑客】','【格斗大师】','【枪弹专家】']\n",
    "enemy_list = ['【暗黑战士】','【黑暗弩手】','【暗夜骑士】','【嗜血刀客】','【首席刺客】','【陷阱之王】']\n",
    "players = random.sample(player_list,3)  \n",
    "enemies = random.sample(enemy_list,3)\n",
    "player_info = {}\n",
    "enemy_info = {}\n",
    "\n",
    "# 随机生成角色的属性\n",
    "def born_role():\n",
    "    life = random.randint(100,180)\n",
    "    attack = random.randint(30,50)\n",
    "    return life,attack\n",
    "\n",
    "# 生成和展示角色信息\n",
    "def show_role():\n",
    "    for i in range(3):\n",
    "        player_info[players[i]] = born_role()\n",
    "        enemy_info[enemies[i]] = born_role()\n",
    "    \n",
    "    # 展示我方的3个角色\n",
    "    print('----------------- 角色信息 -----------------')\n",
    "    print('你的人物：')\n",
    "    for i in range(3):\n",
    "        print('%s  血量：%d  攻击：%d' \n",
    "        %(players[i],player_info[players[i]][0],player_info[players[i]][1]))\n",
    "    print('--------------------------------------------')\n",
    "    print('电脑敌人：')\n",
    "    \n",
    "    # 展示敌方的3个角色\n",
    "    for i in range(3):\n",
    "        print('%s  血量：%d  攻击：%d' \n",
    "        %(enemies[i],enemy_info[enemies[i]][0],enemy_info[enemies[i]][1]))\n",
    "    print('--------------------------------------------')\n",
    "    input('请按回车键继续。\\n')  # 为了让玩家更有控制感，可以插入类似的代码来切分游戏进程。\n",
    "\n",
    "# 角色排序，选择出场顺序。\n",
    "def order_role(): \n",
    "    global players    #设置全局变量\n",
    "    order_dict = {}\n",
    "    for i in range(3):\n",
    "        order = int(input('你想将 %s 放在第几个上场？(输入数字1~3)'% players[i]))\n",
    "        order_dict[order] = players[i]  \n",
    "\n",
    "    players = []\n",
    "    for i in range(1,4):\n",
    "        players.append(order_dict[i]) \n",
    "    \n",
    "    print('\\n我方角色的出场顺序是：%s、%s、%s' %(players[0],players[1],players[2]))\n",
    "    print('敌方角色的出场顺序是：%s、%s、%s' %(enemies[0],enemies[1],enemies[2]))\n",
    "\n",
    "# 角色PK\n",
    "def pk_role(): \n",
    "    round = 1  \n",
    "    score = 0\n",
    "    for i in range(3):  # 一共要打三局\n",
    "        player_name = players[i]  # 统一将下面会用到的数据先赋值给变量会更清晰更好管理\n",
    "        enemy_name = enemies[i] \n",
    "        player_life = player_info[players[i]][0]  \n",
    "        player_attack = player_info[players[i]][1]\n",
    "        enemy_life = enemy_info[enemies[i]][0]\n",
    "        enemy_attack = enemy_info[enemies[i]][1]\n",
    "\n",
    "        # 每一局开战前展示战斗信息\n",
    "        print('\\n----------------- 【第%d局】 -----------------' % round)\n",
    "        print('玩家角色：%s vs 敌方角色：%s ' %(player_name,enemy_name))\n",
    "        print('%s 血量：%d  攻击：%d' %(player_name,player_life,player_attack))\n",
    "        print('%s 血量：%d  攻击：%d' %(enemy_name,enemy_life,enemy_attack))\n",
    "        print('--------------------------------------------')\n",
    "        input('请按回车键继续。\\n')\n",
    "\n",
    "        # 开始判断血量是否都大于零，然后互扣血量。\n",
    "        while player_life > 0 and enemy_life > 0:\n",
    "            enemy_life = enemy_life - player_attack\n",
    "            player_life = player_life - enemy_attack\n",
    "            print('%s发起了攻击，%s剩余血量%d' % (player_name,enemy_name,enemy_life))\n",
    "            print('%s发起了攻击，%s剩余血量%d' % (enemy_name,player_name,player_life))\n",
    "            print('--------------------------------------------')\n",
    "            time.sleep(1)\n",
    "        else:  # 每局的战果展示，以及分数score和局数的变化。\n",
    "            # 调用show_result()函数，打印返回元组中的result。\n",
    "            print(show_result(player_life,enemy_life)[1])\n",
    "            # 调用show_result()函数，完成计分变动。\n",
    "            score += int(show_result(player_life,enemy_life)[0])\n",
    "            round += 1\n",
    "    input('\\n点击回车，查看比赛的最终结果\\n')\n",
    "\n",
    "    if score > 0:\n",
    "        print('【最终结果：你赢了！】\\n')\n",
    "    elif score < 0:\n",
    "        print('【最终结果：你输了！】\\n')\n",
    "    else:\n",
    "        print('【最终结果：平局！】\\n')\n",
    "\n",
    "# 返回单局战果和计分法所加分数。\n",
    "def show_result(player_life,enemy_life):  # 注意：该函数要设定参数，才能判断单局战果。\n",
    "    if player_life > 0 and enemy_life <= 0:\n",
    "        result = '\\n敌人死翘翘了，你赢了！'\n",
    "        return 1,result  # 返回元组(1,'\\n敌人死翘翘了，你赢了！')，类似角色属性的传递。\n",
    "    elif player_life <= 0 and enemy_life > 0:        \n",
    "        result = '\\n悲催，敌人把你干掉了！'\n",
    "        return -1,result\n",
    "    else :\n",
    "        result = '\\n哎呀，你和敌人同归于尽了！'\n",
    "        return 0,result\n",
    "\n",
    "# （主函数）展开战斗流程\n",
    "def main():\n",
    "    show_role()\n",
    "    order_role()\n",
    "    pk_role()\n",
    "\n",
    "# 启动程序（即调用主函数）\n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业10.1\n",
    "import random\n",
    "# 出拳\n",
    "punches = ['石头','剪刀','布']\n",
    "computer_choice = random.choice(punches)\n",
    "while True:\n",
    "    user_choice = input('输入你的选择：')\n",
    "    if user_choice in punches:\n",
    "        break\n",
    "    else :\n",
    "        print('输入错误，请重新出拳')\n",
    "#显示出拳结果\n",
    "print('你出拳为%s \\n电脑出拳为%s'%(user_choice,computer_choice))\n",
    "#判断胜负\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num2 = list(range(1,6))\n",
    "num2.extend('ABCDE') \n",
    "list2 = [m+n for m in ['天字', '地字'] for n in '一二']\n",
    "list3 = [n*n for n in range(1,11) if n % 3 == 0]\n",
    "\n",
    "def cards():\n",
    "    color = ['黑桃','方块','红心','梅花']\n",
    "    num = list(range(2,11))\n",
    "    num.extend('JQKA')\n",
    "    list2 = [[m,n] for m in color for n in num ]\n",
    "    print (list2)\n",
    "cards()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "# 出拳\n",
    "punches = ['石头','剪刀','布']\n",
    "computer_choice = random.choice(punches)\n",
    "user_choice = ''\n",
    "user_choice = input('请出拳：（石头、剪刀、布）')  # 请用户输入选择\n",
    "while user_choice not in punches:  # 当用户输入错误，提示错误，重新输入\n",
    "    print('输入有误，请重新出拳')\n",
    "    user_choice = input()\n",
    "# 亮拳\n",
    "print('————战斗过程————')\n",
    "print('电脑出了：%s' % computer_choice)\n",
    "print('你出了：%s' % user_choice)\n",
    "# 胜负\n",
    "print('—————结果—————')\n",
    "if user_choice == computer_choice:  # 使用if进行条件判断\n",
    "    print('平局！')\n",
    "elif (user_choice == punches[punches.index(computer_choice)-1]):\n",
    "    print('你赢了！')\n",
    "else:\n",
    "    print('你输了！')\n",
    "    \n",
    "    \n",
    "# index 函数使用 ： 索引\n",
    "\n",
    "str1 = \"this is string example..exam..wow!!!\"\n",
    "str2 = \"exam\"\n",
    "print (str1.index(str2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 10    debug\n",
    "\n",
    "a = input('请输入密码：')\n",
    "if a == '123456' \n",
    "    print('通过')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in range(10)：\n",
    "    　print（x）　　"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "while n<3:\n",
    "    username = input(\"请输入用户名：\")\n",
    "    password = input(\"请输入密码：\")\n",
    "    if username == 'abc' and password == '123':\n",
    "        print(\"登录成功\")\n",
    "        break\n",
    "    else:\n",
    "        n=n+1\n",
    "        print(\"输入有误\")\n",
    "else:\n",
    "    print(\"你输错了三次，登录失败\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = []\n",
    "a = append('A')  #append()函数是列表的一个方法，要用句点.调用，且append()每次只能接受一个参数\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "movie = {\n",
    "    '妖猫传':['黄轩','染谷将太'],\n",
    "    '无问西东':['章子怡','王力宏','祖峰'],\n",
    "    '超时空同居':['雷佳音','佟丽娅']\n",
    "}\n",
    "\n",
    "for i in movie:\n",
    "    actors=[i]\n",
    "    print(actors) #使用print() 函数查看操作是否正确。\n",
    "    #if name in actors:\n",
    "        #print(name+'出演了'+i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "guess = ''\n",
    "result = ['正面','反面']\n",
    "while guess not in result:\n",
    "    print('------猜硬币游戏------')\n",
    "    print('猜一猜硬币是正面还是反面？')\n",
    "    guess = input('请输入“正面”或“反面”：')\n",
    "\n",
    "# 随机抛硬币，0代表正面，1代表反面\n",
    "toss = random.randint(0,1)\n",
    "\n",
    "if toss == result.index(guess):\n",
    "    print('猜对了！你真棒')\n",
    "else:\n",
    "    print('没猜对，你还有一次机会。')\n",
    "    guess = input('再输一次“正面”或“反面”：')\n",
    "    if toss == result.index(guess):\n",
    "        print('你终于猜对了！')\n",
    "    else:\n",
    "        print('大失败！')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dir(__builtins__)   # 常见的异常类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### try...except 语句：在异常出现时即时捕获，改变方向让程序继续运行。\n",
    "import traceback\n",
    "while True:\n",
    "    try:\n",
    "        age = int(input('你今年几岁了？'))\n",
    "        break\n",
    "    except ValueError:     #except后面最好加异常类型保证其他不出错\n",
    "        print('你输入的不是数字！')\n",
    "        # traceback.print_exc()       # 将错误信息打印出来\n",
    "        continue\n",
    "    finally:\n",
    "        print('无论是否异常,都执行该语句')\n",
    "if age < 18:\n",
    "    print('不可以喝酒噢')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业11.2\n",
    "print('\\n欢迎使用除法计算器！\\n')\n",
    "while True:\n",
    "    x = input('请你输入除数：')\n",
    "    y = input('请你输入被除数：')\n",
    "    z = float(x)/float(y)\n",
    "    print(x,'/',y,'=',z)\n",
    "    break "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3.7.4 64-bit ('base': conda)"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "interpreter": {
   "hash": "2a7e95a32014fc1ccf24626d45a98c6e7b4373277259c22f47a91d487fc3e8a5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}